package main
{
	import flash.display.Bitmap;
	import flash.geom.Point;
	
	import isometric.GraphicsTile;
	import isometric.IsoUtils;
	import isometric.IsoWorld;
	import isometric.Point3D;
	
	import resource.ResourceDefinition;
	
	import starling.display.DisplayObject;
	import starling.display.DisplayObjectContainer;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.textures.Texture;
	
	public class IsoTest extends DisplayObjectContainer
	{
		private var world:IsoWorld;
		
		public function IsoTest()
		{
			super();
			this.world = new IsoWorld();
			this.addChild(this.world);
			this.world.x = 100;
			this.world.y = 50;
			var bitmap:Bitmap = new ResourceDefinition.Tile_Floor as Bitmap;
			var textrue:Texture = Texture.fromBitmap(bitmap);
			var row:int = 10;
			var clumn:int = 12;
			var house:Texture = Texture.fromBitmap(new ResourceDefinition.Tile_House as Bitmap);
			for(var i:int = 0;i < 120;i++){
				var r:int = i/10;
				var c:int = i%10;
				var gtile:GraphicsTile = new GraphicsTile(30,textrue,30,15);
				gtile.index = i;
				gtile.position = new Point3D(r*30,0,c*30);
				this.world.addChildToFloor(gtile);
			}
			var houseTile:GraphicsTile = new GraphicsTile(60,house,20,45);
			houseTile.position = new Point3D(0,0,0);
			this.world.addChildToWorld(houseTile);
			this.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			this.addEventListener(TouchEvent.TOUCH,onTouch);
		}
		
		private function onTouch(event:TouchEvent):void{
			var touch:Touch = event.getTouch(stage);
			if(touch != null && touch.phase == TouchPhase.HOVER){
				trace("over : ");
				trace(event.target);
				var global:Point = new Point(touch.globalX,touch.globalY);
				var local:Point = new Point();
				global.y = global.y + 15;
				this.world.globalToLocal(global,local);
				trace("global : " + global.x + ";" + global.y);
				trace("local : " + local.x + ";" + local.y);
				var index:int = 0;
				var point3d:Point3D = IsoUtils.screenToIso(local);
//				point3d.z = point3d.z + 15;
				index = getTileIndex(point3d);
				this.world.updateFloorByIndex(index);
				trace("index : " + index);
			}else if (touch != null && touch.phase == TouchPhase.BEGAN){
//				trace(event.target);
			}
		}
		
		
		private function getTileIndex(point3d:Point3D):int{
			var result:int = 0;
			var r:int = Math.floor(point3d.x/30);
			var c:int = Math.floor(point3d.z/30);
			result = r * 10 + c;
			return result;
		}
		
		private function onEnterFrame(event:Event):void{
			
		}
	}
}